package com.leesche.zcsp.node.app.v1.controller.register;

import com.leesche.zcsp.node.app.v1.constants.AppContants;
import com.leesche.zcsp.node.app.v1.timer.PhoneCodeCacheTimer;
import com.leesche.zcsp.node.app.v1.timer.VaildPhone;
import com.leesche.zcsp.node.communication.service.SmsService;
import com.leesche.zcsp.node.pay.wecha.data.Message;
import com.leesche.zcsp.node.utils.security.QEncodeUtil;
import com.leesche.zcsp.node.utils.web.gernerator.MobileCodeGernerator;
import com.leesche.zcsp.node.utils.web.messge.WebResult;
import com.leesche.zcsp.node.web.constants.Constants;
import com.leesche.zcsp.node.web.model.SysUser;
import com.leesche.zcsp.node.web.model.SysUserCriteria;
import com.leesche.zcsp.node.web.service.SysUserService;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @author Jerry Chan
 * @version V1.0
 *          ************ * Jerry Chan: * 2016/12/1 18:23: * 创建该类并实现业务逻辑: *********
 * @Title: AppForgetPwdController.java
 * @Description: TODO(用户注册->找回密码Controller类)
 * @date 2016/12/1 18:23
 */
@Controller
@RequestMapping(value = "/app/v1/register")
public class AppForgetPwdController {


    private static final Logger logger = Logger
            .getLogger(AppForgetPwdController.class);

    @Autowired
    private SmsService smsService;

    @Autowired
    private SysUserService sysUserService;

    /** 
     * @Title: forgetPassword(Long smsCode,String username, String password)
     * @Description: TODO( 用户找回密码 )
     * @author Jerry Chan
     * @date 2016/12/1 19:56
     */
    @ResponseBody
    @RequestMapping(value = "forgetPassword", method = RequestMethod.POST)
    public Map<String, Object> forgetPassword(String smsCode,String username, String password) {

        try {
            if (smsCode == null || "".equals(smsCode)) {
                return WebResult.failure("短信验证码不能为空").toMap();
            }

            if (username == null || "".equals(username)) {
                return WebResult.failure("用户名不能为空").toMap();
            }

            if (password == null || "".equals(password)) {
                return WebResult.failure("密码不能为空").toMap();
            }

            //Long code = AppContants.PHONE_CODE.get(smsCode);
            //Long code = PhoneCodeCacheTimer.phone_code.get(smsCode);
            VaildPhone vaildPhone = PhoneCodeCacheTimer.get(smsCode);
            if(vaildPhone == null){
                return WebResult.failure("短信验证码错误，请重新输入").toMap();
            }else if(vaildPhone.getValidTime() < new Date().getTime()){
                PhoneCodeCacheTimer.remove(smsCode);
                return WebResult.failure("短信验证码已过期，请重新获取").toMap();
            }

            SysUserCriteria criteria = new SysUserCriteria();
            criteria.or().andUsernameEqualTo(username);
            SysUser user = new SysUser();
            user.setPassword(QEncodeUtil.md5Encrypt(password));
            int result = sysUserService.updateByCriteriaSelective(user,criteria);
            if(result > 0)
                return WebResult.success().toMap();
            else
                return WebResult.failure("找回密码失败，请稍后重试").toMap();
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            return WebResult.failure(Constants.SYSTEM_ERROR_PROMPT_MSG).toMap();
        }
    }

    /**
     * @Title: validUser(String mobilenumber, String username)
     * @Description: TODO( 验证用户名和手机号是否存在 )
     * @author Jerry Chan
     * @date 2016/12/1 19:23
     */
    @ResponseBody
    @RequestMapping(value = "validuser", method = RequestMethod.POST)
    public Map<String, Object> validUser(String mobilenumber, String username) {

        try {

            if (mobilenumber == null || "".equals(mobilenumber)) {
                return WebResult.failure("手机号码不能为空").toMap();
            }

            if (username == null || "".equals(username)) {
                return WebResult.failure("用户名不能为空").toMap();
            }

            SysUser user = new SysUser();
            user.setUsername(username);
            user =  sysUserService.findUserByUsername(user);

            if(user == null){
                return WebResult.failure("用户名不存在").toMap();
            }

            if(!mobilenumber.equals(user.getMobile())){
                return WebResult.failure("手机号码与用户名不匹配").toMap();
            }

            return this.beginSendMsg(user.getMobile());

        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            return WebResult.failure(Constants.SYSTEM_ERROR_PROMPT_MSG).toMap();
        }
    }

    /**
     * @param mobileNum 手机号码
     * @return 发送短信结果
     * @Title: beginSendMsg(String mobileNum, HttpSession session)
     * @Description: TODO(开始发送短信)
     * @author Jerry
     * @date 2016-10-29 10:35:55
     */
    private Map<String, Object> beginSendMsg(String mobileNum) throws Exception {
        //生成随机码
        String mobileCode = MobileCodeGernerator.mobileCodeGernerator();
        //发送短信
        Message<String> smsReport = smsService.sendSMS(mobileNum, mobileCode);
        //存在到session 发送成功
        if (Message.isSuccess(smsReport.getType())) {
            //有效时间
            long validTime = new Date().getTime() + (Constants.NOTIC_DEFAULT_MOBLIE_CODE_MAXINACTIVEINTERVAL * 60000);
            //保存短信验证码
            //AppContants.PHONE_CODE.put(mobileCode, validTime);
            VaildPhone vaildPhone = new VaildPhone(validTime,mobileNum);
            PhoneCodeCacheTimer.put(mobileCode, vaildPhone);
            return WebResult.success().info(Constants.getMobileCodeVaildMsg(mobileNum)).toMap();
        } else {
            String errMag = smsReport.getContent();
            if("InvalidRecNum.Malformed".equals(errMag)){
                return WebResult.failure("手机号不正确,请输入正确的手机号码").toMap();
            } else if ("InvalidSendSms".equals(errMag)){
                return WebResult.failure("获取短信过于频繁,请稍后重试").toMap();
            } else {
                return WebResult.failure(Constants.SYSTEM_ERROR_PROMPT_MSG).toMap();
            }
        }
        //记录短信发送内容
    }

}
